/*
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

/*
 *
 *
 *
 *
 *
 * Written by Josh Bloch of Google Inc. and released to the public domain,
 * as explained at http://creativecommons.org/publicdomain/zero/1.0/.
 */

package java.util;

import java.io.Serializable;
import java.util.function.Consumer;

import sun.misc.SharedSecrets;

/**
 * 1、底层数组实现，
 * 2、为了满足在数组两端同时插入或删除的需求，该数组必须是循环数组，
 * 也就是说数组的任何一点都可以被看作起点和终点。
 * 3、非线程安全的
 * 4、不允许null值
 */
public class ArrayDeque<E> extends AbstractCollection<E>
        implements Deque<E>, Cloneable, Serializable {


    /**
     * 存储双端队列元素的数组。
     * 双端队列的容量是此数组的长度，且总是2的幂。数组永远不会被允许完全填满，
     * 除非在某个 `addX` 方法中短暂地变满，在这种情况下会立即调整大小（参见 `doubleCapacity`），
     * 从而避免头和尾绕回到相同的位置。我们还保证所有不存储双端队列元素的数组单元始终为 null。
     */
    transient Object[] elements; // 非私有以简化嵌套类访问


    /**
     * head指向首端第一个有效元素
     * 双端队列头部元素的索引（即通过 `remove()` 或 `pop()` 方法将被移除的元素）；
     * 如果双端队列为空，则为一个任意值，等于 `tail`。
     */
    transient int head;


    /**
     * tail指向尾端第一个可以插入元素的空位
     * 下一个元素将被添加到双端队列尾部的索引（通过 `addLast(E)`、`add(E)` 或 `push(E)` 方法）。
     */
    transient int tail;


    /**
     * 新创建的双端队列的最小容量。
     * 必须是2的幂。
     */
    private static final int MIN_INITIAL_CAPACITY = 8;


    // 构造函数

    /**
     * 构造一个初始容量足以容纳16个元素的空数组双端队列。
     */
    public ArrayDeque() {
        elements = new Object[16];
    }

    /**
     * 构造一个初始容量足以容纳指定数量元素的空数组双端队列。
     *
     * @param numElements 双端队列的初始容量下限
     */
    public ArrayDeque(int numElements) {
        allocateElements(numElements);
    }

    /**
     * 构造一个包含指定集合中元素的双端队列，元素顺序与集合迭代器返回的顺序相同。
     * （集合迭代器返回的第一个元素将成为双端队列的第一个元素，即双端队列的前端。）
     *
     * @param c 要放入双端队列中的集合
     * @throws NullPointerException 如果指定的集合为 null
     */
    public ArrayDeque(Collection<? extends E> c) {
        allocateElements(c.size());
        addAll(c);
    }


    /**
     * 分配一个空数组来存储指定数量的元素。
     *
     * @param numElements 要存储的元素数量
     */
    private void allocateElements(int numElements) {
        elements = new Object[calculateSize(numElements)];
    }


    // ******  Array allocation and resizing utilities ******

    /*
     * 创建2的幂次方数组大小有几个重要的原因：
     * 内存对齐和缓存友好：
     * 在许多现代计算机架构中，2的幂次方大小的内存分配更高效。这是因为内存管理器通常会将内存块对齐到2的幂次方边界，这样可以减少内存碎片并提高缓存命中率。
     * 哈希表性能优化：
     * 对于哈希表（如Java中的HashMap），使用2的幂次方大小可以简化索引计算。例如，使用位运算代替取模运算可以显著提高性能。具体来说，对于大小为2的幂次方的数组，可以通过 index & (size - 1) 来计算索引，而不是使用更慢的 index % size。
     * 动态扩展：
     * 当数组需要扩展时，选择2的幂次方大小可以确保每次扩展时数组大小翻倍。这种策略可以减少重新分配和复制数据的频率，从而提高整体性能。
     * 避免溢出：
     * 使用2的幂次方可以更容易地处理大数，避免在计算过程中发生溢出。例如，通过逐步右移和按位或操作，可以确保最终结果不会超过int的最大值。
     * 综上所述，使用2的幂次方大小的数组在性能和内存管理方面都有显著的优势。
     */

    /**
     * 计算给定元素数量所需的最优数组大小。
     * 该方法旨在找到一个最合适的容量（2的幂），以容纳给定数量的元素。
     * 它确保数组有足够空间，同时考虑空间利用效率。
     *
     * @param numElements 需要容纳的元素数量。
     * @return 最优数组大小。
     */
    private static int calculateSize(int numElements) {
        // 初始化最小初始容量。
        int initialCapacity = MIN_INITIAL_CAPACITY;
        // 查找能够容纳元素的最佳2的幂。
        // 测试 "<=" 是因为数组不会被完全填满。
        if (numElements >= initialCapacity) {
            // 确保有足够的容量，通过计算大于 numElements 的最小2的幂。
            initialCapacity = numElements;
            initialCapacity |= (initialCapacity >>> 1);
            initialCapacity |= (initialCapacity >>> 2);
            initialCapacity |= (initialCapacity >>> 4);
            initialCapacity |= (initialCapacity >>> 8);
            initialCapacity |= (initialCapacity >>> 16);
            initialCapacity++;

            // 如果计算出的容量超过了int的最大值，进行调整以防止溢出。
            if (initialCapacity < 0)   // 元素太多，必须回退
                initialCapacity >>>= 1;// 好运分配 2 ^ 30 个元素
        }
        // 返回计算出的或默认的初始容量。
        return initialCapacity;
    }


    /**
     * 将此双端队列的容量加倍。仅在队列已满时调用，即当头指针和尾指针已经绕回到相同位置时。
     */
    private void doubleCapacity() {
        assert head == tail;                 // 断言头指针和尾指针相等，确保队列已满
        int p = head;                        // 当前头指针的位置
        int n = elements.length;             // 当前数组的长度
        int r = n - p;                       // 头指针右侧的元素数量
        int newCapacity = n << 1;            // 新的容量为当前容量的两倍
        if (newCapacity < 0)
            throw new IllegalStateException("对不起，双端队列太大"); // 如果新的容量超出int范围，抛出异常
        Object[] a = new Object[newCapacity];                // 创建新的数组
        System.arraycopy(elements, p, a, 0, r);      // 将头指针右侧的元素复制到新数组的开头
        System.arraycopy(elements, 0, a, r, p);       // 将头指针左侧的元素复制到新数组的相应位置
        elements = a; // 更新引用到新数组
        head = 0;     // 重置头指针
        tail = n;     // 重置尾指针
    }


    /**
     * Copies the elements from our element array into the specified array,
     * in order (from first to last element in the deque).  It is assumed
     * that the array is large enough to hold all elements in the deque.
     *
     * @return its argument
     */
    private <T> T[] copyElements(T[] a) {
        if (head < tail) {
            System.arraycopy(elements, head, a, 0, size());
        } else if (head > tail) {
            int headPortionLen = elements.length - head;
            System.arraycopy(elements, head, a, 0, headPortionLen);
            System.arraycopy(elements, 0, a, headPortionLen, tail);
        }
        return a;
    }


    // The main insertion and extraction methods are addFirst,
    // addLast, pollFirst, pollLast. The other methods are defined in
    // terms of these.

    /**
     * 首端插入数据 数据不能为null
     */
    public void addFirst(E e) {
        if (e == null)
            throw new NullPointerException();
        elements[head = (head - 1) & (elements.length - 1)] = e; //这段代码相当于取余，同时解决了head为负值的情况。
        if (head == tail)
            doubleCapacity();
    }

    /**
     * 尾端插入数据 数据不能为null
     */
    public void addLast(E e) {
        if (e == null)
            throw new NullPointerException();
        elements[tail] = e;  // 先插入后检查空间,若tail == head就扩容
        if ((tail = (tail + 1) & (elements.length - 1)) == head) // 如果tail是队列长度，则会自动回绕到0
            doubleCapacity();
    }


    /**
     * 首端插入数据 数据不能为null
     * 添加成功后返回true
     */
    public boolean offerFirst(E e) {
        addFirst(e);
        return true;
    }

    /**
     * 尾端插入数据 数据不能为null
     * 添加成功后返回true
     */
    public boolean offerLast(E e) {
        addLast(e);
        return true;
    }

    /**
     * 删除首位元素
     */
    public E removeFirst() {
        E x = pollFirst();
        if (x == null)
            throw new NoSuchElementException();
        return x;
    }

    /**
     * 删除末尾元素
     */
    public E removeLast() {
        E x = pollLast();
        if (x == null)
            throw new NoSuchElementException();
        return x;
    }

    /**
     * 删除并返回Deque首端元素
     */
    public E pollFirst() {
        int h = head;
        @SuppressWarnings("unchecked")
        E result = (E) elements[h];
        // Element is null if deque empty
        if (result == null)
            return null;
        elements[h] = null;     // Must null out slot
        head = (h + 1) & (elements.length - 1);
        return result;
    }

    /**
     * 删除并返回Deque尾端元素
     */
    public E pollLast() {
        int t = (tail - 1) & (elements.length - 1);
        @SuppressWarnings("unchecked")
        E result = (E) elements[t];
        if (result == null)
            return null;
        elements[t] = null;
        tail = t;
        return result;
    }


    /**
     * 获取首位元素
     */
    public E getFirst() {
        @SuppressWarnings("unchecked")
        E result = (E) elements[head];
        if (result == null)
            throw new NoSuchElementException();
        return result;
    }

    /**
     * 获取末尾元素
     */
    public E getLast() {
        @SuppressWarnings("unchecked")
        E result = (E) elements[(tail - 1) & (elements.length - 1)];
        if (result == null)
            throw new NoSuchElementException();
        return result;
    }

    @SuppressWarnings("unchecked")
    /**
     * 返回但不删除Deque首端元素
     */
    public E peekFirst() {
        // elements[head] is null if deque empty
        return (E) elements[head];
    }

    @SuppressWarnings("unchecked")
    /**
     * 返回但不删除Deque末端元素
     */
    public E peekLast() {
        return (E) elements[(tail - 1) & (elements.length - 1)];
    }


    public boolean removeFirstOccurrence(Object o) {
        if (o == null)
            return false;
        int mask = elements.length - 1;
        int i = head;
        Object x;
        while ((x = elements[i]) != null) {
            if (o.equals(x)) {
                delete(i);
                return true;
            }
            i = (i + 1) & mask;
        }
        return false;
    }


    public boolean removeLastOccurrence(Object o) {
        if (o == null)
            return false;
        int mask = elements.length - 1;
        int i = (tail - 1) & mask;
        Object x;
        while ((x = elements[i]) != null) {
            if (o.equals(x)) {
                delete(i);
                return true;
            }
            i = (i - 1) & mask;
        }
        return false;
    }






    // *** Queue methods 先进后出 ***
    public boolean add(E e) {
        addLast(e);
        return true;
    }
    public boolean offer(E e) {
        return offerLast(e);
    } // 只向末尾添加数据
    public E remove() {return removeFirst();}
    public E poll() {
        return pollFirst();
    } // 只获取首位数据
    public E element() {
        return getFirst();
    }
    public E peek() {
        return peekFirst();
    }




    // *** Stack methods  先进先出***


    public void push(E e) {
        addFirst(e);
    }
    public E pop() {return removeFirst();}

    private void checkInvariants() {
        assert elements[tail] == null;
        assert head == tail ? elements[head] == null :
                (elements[head] != null &&
                        elements[(tail - 1) & (elements.length - 1)] != null);
        assert elements[(head - 1) & (elements.length - 1)] == null;
    }
    private boolean delete(int i) {
        checkInvariants();
        final Object[] elements = this.elements;
        final int mask = elements.length - 1;
        final int h = head;
        final int t = tail;
        final int front = (i - h) & mask;
        final int back = (t - i) & mask;

        // Invariant: head <= i < tail mod circularity
        if (front >= ((t - h) & mask))
            throw new ConcurrentModificationException();

        // Optimize for least element motion
        if (front < back) {
            if (h <= i) {
                System.arraycopy(elements, h, elements, h + 1, front);
            } else { // Wrap around
                System.arraycopy(elements, 0, elements, 1, i);
                elements[0] = elements[mask];
                System.arraycopy(elements, h, elements, h + 1, mask - h);
            }
            elements[h] = null;
            head = (h + 1) & mask;
            return false;
        } else {
            if (i < t) { // Copy the null tail as well
                System.arraycopy(elements, i + 1, elements, i, back);
                tail = t - 1;
            } else { // Wrap around
                System.arraycopy(elements, i + 1, elements, i, mask - i);
                elements[mask] = elements[0];
                System.arraycopy(elements, 1, elements, 0, t);
                tail = (t - 1) & mask;
            }
            return true;
        }
    }






    // *** Collection Methods ***
    public int size() {
        return (tail - head) & (elements.length - 1);
    }
    public boolean isEmpty() {
        return head == tail;
    }
    public Iterator<E> iterator() {
        return new DeqIterator();
    }
    public Iterator<E> descendingIterator() {
        return new DescendingIterator();
    }

    private class DeqIterator implements Iterator<E> {
        /**
         * Index of element to be returned by subsequent call to next.
         */
        private int cursor = head;

        /**
         * Tail recorded at construction (also in remove), to stop
         * iterator and also to check for comodification.
         */
        private int fence = tail;

        /**
         * Index of element returned by most recent call to next.
         * Reset to -1 if element is deleted by a call to remove.
         */
        private int lastRet = -1;

        public boolean hasNext() {
            return cursor != fence;
        }

        public E next() {
            if (cursor == fence)
                throw new NoSuchElementException();
            @SuppressWarnings("unchecked")
            E result = (E) elements[cursor];
            // This check doesn't catch all possible comodifications,
            // but does catch the ones that corrupt traversal
            if (tail != fence || result == null)
                throw new ConcurrentModificationException();
            lastRet = cursor;
            cursor = (cursor + 1) & (elements.length - 1);
            return result;
        }

        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            if (delete(lastRet)) { // if left-shifted, undo increment in next()
                cursor = (cursor - 1) & (elements.length - 1);
                fence = tail;
            }
            lastRet = -1;
        }

        public void forEachRemaining(Consumer<? super E> action) {
            Objects.requireNonNull(action);
            Object[] a = elements;
            int m = a.length - 1, f = fence, i = cursor;
            cursor = f;
            while (i != f) {
                @SuppressWarnings("unchecked") E e = (E) a[i];
                i = (i + 1) & m;
                if (e == null)
                    throw new ConcurrentModificationException();
                action.accept(e);
            }
        }
    }

    private class DescendingIterator implements Iterator<E> {
        /*
         * This class is nearly a mirror-image of DeqIterator, using
         * tail instead of head for initial cursor, and head instead of
         * tail for fence.
         */
        private int cursor = tail;
        private int fence = head;
        private int lastRet = -1;

        public boolean hasNext() {
            return cursor != fence;
        }

        public E next() {
            if (cursor == fence)
                throw new NoSuchElementException();
            cursor = (cursor - 1) & (elements.length - 1);
            @SuppressWarnings("unchecked")
            E result = (E) elements[cursor];
            if (head != fence || result == null)
                throw new ConcurrentModificationException();
            lastRet = cursor;
            return result;
        }

        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            if (!delete(lastRet)) {
                cursor = (cursor + 1) & (elements.length - 1);
                fence = head;
            }
            lastRet = -1;
        }
    }


    public boolean contains(Object o) {
        if (o == null)
            return false;
        int mask = elements.length - 1;
        int i = head;
        Object x;
        while ((x = elements[i]) != null) {
            if (o.equals(x))
                return true;
            i = (i + 1) & mask;
        }
        return false;
    }

    public boolean remove(Object o) {
        return removeFirstOccurrence(o);
    }

    public void clear() {
        int h = head;
        int t = tail;
        if (h != t) { // clear all cells
            head = tail = 0;
            int i = h;
            int mask = elements.length - 1;
            do {
                elements[i] = null;
                i = (i + 1) & mask;
            } while (i != t);
        }
    }

    public Object[] toArray() {
        return copyElements(new Object[size()]);
    }

    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
        int size = size();
        if (a.length < size)
            a = (T[]) java.lang.reflect.Array.newInstance(
                    a.getClass().getComponentType(), size);
        copyElements(a);
        if (a.length > size)
            a[size] = null;
        return a;
    }



    // *** Object methods ***

    public ArrayDeque<E> clone() {
        try {
            @SuppressWarnings("unchecked")
            ArrayDeque<E> result = (ArrayDeque<E>) super.clone();
            result.elements = Arrays.copyOf(elements, elements.length);
            return result;
        } catch (CloneNotSupportedException e) {
            throw new AssertionError();
        }
    }

    private static final long serialVersionUID = 2340985798034038923L;

    private void writeObject(java.io.ObjectOutputStream s)
            throws java.io.IOException {
        s.defaultWriteObject();

        // Write out size
        s.writeInt(size());

        // Write out elements in order.
        int mask = elements.length - 1;
        for (int i = head; i != tail; i = (i + 1) & mask)
            s.writeObject(elements[i]);
    }

    private void readObject(java.io.ObjectInputStream s)
            throws java.io.IOException, ClassNotFoundException {
        s.defaultReadObject();

        // Read in size and allocate array
        int size = s.readInt();
        int capacity = calculateSize(size);
        SharedSecrets.getJavaOISAccess().checkArray(s, Object[].class, capacity);
        allocateElements(size);
        head = 0;
        tail = size;

        // Read in all elements in the proper order.
        for (int i = 0; i < size; i++)
            elements[i] = s.readObject();
    }

    public Spliterator<E> spliterator() {
        return new DeqSpliterator<E>(this, -1, -1);
    }

    static final class DeqSpliterator<E> implements Spliterator<E> {
        private final ArrayDeque<E> deq;
        private int fence;  // -1 until first use
        private int index;  // current index, modified on traverse/split

        /**
         * Creates new spliterator covering the given array and range
         */
        DeqSpliterator(ArrayDeque<E> deq, int origin, int fence) {
            this.deq = deq;
            this.index = origin;
            this.fence = fence;
        }

        private int getFence() { // force initialization
            int t;
            if ((t = fence) < 0) {
                t = fence = deq.tail;
                index = deq.head;
            }
            return t;
        }

        public DeqSpliterator<E> trySplit() {
            int t = getFence(), h = index, n = deq.elements.length;
            if (h != t && ((h + 1) & (n - 1)) != t) {
                if (h > t)
                    t += n;
                int m = ((h + t) >>> 1) & (n - 1);
                return new DeqSpliterator<>(deq, h, index = m);
            }
            return null;
        }

        public void forEachRemaining(Consumer<? super E> consumer) {
            if (consumer == null)
                throw new NullPointerException();
            Object[] a = deq.elements;
            int m = a.length - 1, f = getFence(), i = index;
            index = f;
            while (i != f) {
                @SuppressWarnings("unchecked") E e = (E) a[i];
                i = (i + 1) & m;
                if (e == null)
                    throw new ConcurrentModificationException();
                consumer.accept(e);
            }
        }

        public boolean tryAdvance(Consumer<? super E> consumer) {
            if (consumer == null)
                throw new NullPointerException();
            Object[] a = deq.elements;
            int m = a.length - 1, f = getFence(), i = index;
            if (i != fence) {
                @SuppressWarnings("unchecked") E e = (E) a[i];
                index = (i + 1) & m;
                if (e == null)
                    throw new ConcurrentModificationException();
                consumer.accept(e);
                return true;
            }
            return false;
        }

        public long estimateSize() {
            int n = getFence() - index;
            if (n < 0)
                n += deq.elements.length;
            return (long) n;
        }

        @Override
        public int characteristics() {
            return Spliterator.ORDERED | Spliterator.SIZED |
                    Spliterator.NONNULL | Spliterator.SUBSIZED;
        }
    }

}
